<?php
class Location extends AppModel {
	public $name = 'Location';
    public $validate = array(
        'parent_id' => array(
            'rule'       => 'numeric',
            'allowEmpty' => true
        ),
        'name' => array(
            'rule'    => array('between', 3, 255),
            'message' => 'Location must be between 3 and 255 characters long'
        ),
        'zip' => array(
            'rule'       => array('between', 2, 20),
            'allowEmpty' => true,
            'message'    => 'Zip code must be between 2 and 20 characters long'
        ),
        'timezone' => array(
            'rule'       => array('range', -12, 13),
            'allowEmpty' => true,
            'message'    => 'Please select a timezone between -12 and +13'
        )
    );
    public $hasMany = array(
        'AdPost'
        /*'City' => array(
            'className'  => 'Location',
            'foreignKey' => 'parent_id',
            'conditions' => 'City.parent_id IS NOT NULL',
            'Location'   => array('dependent' => true)
        )*/
    );
    public $belongsTo = array(
        'Country',
        'State' => array(
            'className'  => 'Location',
            'foreignKey' => 'parent_id'
        )

    );

    public function getCountry ($id) {
        $data = $this->query('SELECT `name`, `code2` FROM `countries` AS Country WHERE `id`='.$id);
        return $data[0]['Country'];
    } // getCountry

    public function totalCountryAdvs ($id) {
        $data = $this->query('SELECT `id` FROM `locations` AS `Location` WHERE `country_id`='.$id.' ORDER BY `id` ASC');
        $loc  = array();

        App::import('Model', 'AdPost');
        $post = new AdPost();

        foreach ($data as $location) {
            $id = $location['Location']['id'];

            $count = $post->find('count', array(
                'conditions' => 'location_id='.$id,
                'recursive'  => -1
            ));
            $loc[$id] = $count;
        }

        return $loc;
    } // totalCountryAdvs
} // Location
?>